import traceback
from datetime import datetime as py_datetime

import yaml

import yaml
from PyQt5.QtCore import Qt

from PyQt5.QtWidgets import QTableWidgetItem, QCheckBox, QTableWidget


def read_yaml(file_path):
    with open(file_path, 'r') as file:
        config = yaml.safe_load(file)
    return config

# # 使用
# data = read_yaml('config.yml')
# print(data)
#
# # 示例假设 config.yml 内容如下：
# # ---
# # database:
# #   host: localhost
# #   port: 5432
# #   user: myuser
# #   password: mypassword
# # 运行后，data变量会是一个字典结构：
# # {'database': {'host': 'localhost', 'port': 5432, 'user': 'myuser', 'password': 'mypassword'}}


def write_yaml(data, file_path):
    with open(file_path, 'w') as file:
        yaml.safe_dump(data, file)

# # 创建一个字典并写入文件
# config_data = {
#     'database': {
#         'host': 'localhost',
#         'port': 5432,
#         'user': 'newuser',
#         'password': 'newpassword'
#     }
# }
# write_yaml(config_data, 'config_output.yml')

class ui_util:

    @staticmethod
    def tableValue2tableObj(det_record_kv_list, tableWidget):
        '''
        显示数据到表格 （覆盖原来的）
        tableWidget： 表格控件
        det_record_kv_list： 数据 [{},{}]
        :return:
        '''
        try:
            # print('xxxxxxxxxxxxxxx')
            # 获取当前表格的行数
            num_rows = tableWidget.rowCount()
            # 从后往前遍历并删除每一行，以避免因删除行导致索引变动
            for row in reversed(range(num_rows)):
                tableWidget.removeRow(row)

            for row_ind, kv_dict in enumerate(det_record_kv_list): # 每行
                tableWidget.insertRow(row_ind)  # 添加新行
                for col_ind, (k,v) in enumerate(kv_dict.items()): # 每列 按dict的key值创建顺序
                    if isinstance(v,bool): # 复选框
                        # 创建一个不可编辑的 QCheckBox
                        checkbox = QCheckBox()
                        checkbox.setCheckState(Qt.Checked if v else Qt.Unchecked)  # 假设复选框处于选中状态
                        checkbox.setEnabled(False)  # 设置 QCheckBox 为不可编辑, 颜色变为灰色
                        tableWidget.setCellWidget(row_ind, col_ind, checkbox)  # 将 QCheckBox 设置为单元格小部件

                        # checkbox_item = QTableWidgetItem()
                        # checkbox_item.setCheckState(Qt.Checked if v else Qt.Unchecked)  # 根据 bool 变量设置初始状态
                        # # checkbox_item.setFlags(checkbox_item.flags() & ~Qt.ItemIsEditable)  # 禁止编辑
                        # tableWidget.setItem(row_ind, col_ind, checkbox_item)

                    elif isinstance(v, py_datetime):
                        tableWidget.setItem(row_ind, col_ind, QTableWidgetItem(str(v.strftime('%Y/%m/%d %H:%M:%S'))))
                    else:
                        tableWidget.setItem(row_ind, col_ind, QTableWidgetItem(str(v)))

                # break
            # 设置整个表格禁止编辑（可选，如果需要的话）
            tableWidget.setEditTriggers(QTableWidget.NoEditTriggers)
        except:
            print(traceback.format_exc())